// 全局配置
const GLOBAL_CONFIG = {
    // 客户端ID - 统一管理
    CLIENT_ID: 'af4ec6074c07e5a175b94c975bbb0d18',
    // API基础地址
    API_BASE_URL: 'http://localhost:8080'
    // API_BASE_URL: 'http://123.56.57.217/api'
};

// 平滑滚动到指定元素
function smoothScrollTo(element, duration = 600) {
    const targetPosition = element.getBoundingClientRect().top + window.pageYOffset;
    const startPosition = window.pageYOffset;
    const distance = targetPosition - startPosition;
    let startTime = null;
    
    function animation(currentTime) {
        if (startTime === null) startTime = currentTime;
        const timeElapsed = currentTime - startTime;
        const run = ease(timeElapsed, startPosition, distance, duration);
        window.scrollTo(0, run);
        if (timeElapsed < duration) requestAnimationFrame(animation);
    }
    
    function ease(t, b, c, d) {
        t /= d / 2;
        if (t < 1) return c / 2 * t * t + b;
        t--;
        return -c / 2 * (t * (t - 2) - 1) + b;
    }
    
    requestAnimationFrame(animation);
}

// 涟漪效果
function createRipple(event, element) {
    const ripple = document.createElement('span');
    const rect = element.getBoundingClientRect();
    const size = Math.max(rect.width, rect.height);
    const x = event.clientX - rect.left - size / 2;
    const y = event.clientY - rect.top - size / 2;
    
    ripple.style.width = ripple.style.height = size + 'px';
    ripple.style.left = x + 'px';
    ripple.style.top = y + 'px';
    ripple.style.position = 'absolute';
    ripple.style.borderRadius = '50%';
    ripple.style.backgroundColor = 'rgba(255, 255, 255, 0.3)';
    ripple.style.transform = 'scale(0)';
    ripple.style.animation = 'ripple 0.6s ease-out';
    ripple.style.pointerEvents = 'none';
    
    element.style.position = 'relative';
    element.style.overflow = 'hidden';
    element.appendChild(ripple);
    
    setTimeout(() => {
        ripple.remove();
    }, 600);
}

// Toast消息队列管理
const toastQueue = [];
let toastContainer = null;

// 初始化Toast容器
function initToastContainer() {
    if (!toastContainer) {
        toastContainer = document.createElement('div');
        toastContainer.id = 'toast-container';
        toastContainer.className = 'fixed top-4 left-1/2 transform -translate-x-1/2 z-50 pointer-events-none';
        toastContainer.style.maxWidth = '90vw';
        document.body.appendChild(toastContainer);
    }
}

// 显示Toast消息
function showToast(message, type = 'info', options = {}) {
    initToastContainer();
    
    const {
        duration = 3000,
        closable = false
    } = options;
    
    const toast = document.createElement('div');
    toast.className = `mb-2 px-6 py-3 rounded-xl text-white shadow-xl transition-all duration-300 pointer-events-auto`;
    
    const colors = {
        info: 'bg-primary',
        success: 'bg-success',
        warning: 'bg-accent',
        error: 'bg-danger'
    };
    
    toast.classList.add(colors[type] || colors.info);
    
    // 创建消息内容
    const messageText = document.createElement('span');
    messageText.textContent = message;
    toast.appendChild(messageText);
    
    // 添加关闭按钮（如果启用）
    if (closable) {
        const closeBtn = document.createElement('button');
        closeBtn.innerHTML = '×';
        closeBtn.className = 'ml-2 text-white hover:text-gray-200 text-lg font-bold';
        closeBtn.style.cssText = 'line-height: 1; padding: 0; background: none; border: none; cursor: pointer; float: right;';
        
        closeBtn.onclick = (e) => {
            e.stopPropagation();
            removeToast(toast);
        };
        
        toast.appendChild(closeBtn);
    }
    
    // 计算位置
    const currentIndex = toastQueue.length;
    const topPosition = currentIndex * 60; // 每个Toast间距60px
    
    // 设置初始位置和样式
    toast.style.position = 'relative';
    toast.style.top = `${topPosition}px`;
    toast.style.opacity = '0';
    toast.style.transform = 'translateY(-20px)';
    toast.style.marginBottom = '8px';
    
    // 添加到队列和DOM
    toastQueue.push(toast);
    toastContainer.appendChild(toast);
    
    // 显示动画
    setTimeout(() => {
        toast.style.opacity = '1';
        toast.style.transform = 'translateY(0)';
    }, 10);
    
    // 自动隐藏
    if (duration > 0) {
        setTimeout(() => {
            removeToast(toast);
        }, duration);
    }
    
    return toast;
}

// 移除Toast
function removeToast(toast) {
    if (!toast || !toast.parentNode) return;
    
    const index = toastQueue.indexOf(toast);
    if (index === -1) return;
    
    // 隐藏动画
    toast.style.opacity = '0';
    toast.style.transform = 'translateY(-20px)';
    
    setTimeout(() => {
        if (toast.parentNode) {
            toast.parentNode.removeChild(toast);
        }
        
        // 从队列中移除
        toastQueue.splice(index, 1);
        
        // 重新计算剩余Toast的位置
        toastQueue.forEach((remainingToast, newIndex) => {
            if (remainingToast.parentNode) {
                remainingToast.style.top = `${newIndex * 60}px`;
            }
        });
    }, 300);
}

// 清除所有Toast
function clearAllToasts() {
    toastQueue.forEach(toast => {
        if (toast.parentNode) {
            toast.parentNode.removeChild(toast);
        }
    });
    toastQueue.length = 0;
}

// 格式化日期
function formatDate(date) {
    const now = new Date();
    const diff = now - date;
    const seconds = Math.floor(diff / 1000);
    const minutes = Math.floor(seconds / 60);
    const hours = Math.floor(minutes / 60);
    const days = Math.floor(hours / 24);
    
    if (seconds < 60) return '刚刚';
    if (minutes < 60) return `${minutes}分钟前`;
    if (hours < 24) return `${hours}小时前`;
    if (days < 7) return `${days}天前`;
    
    return date.toLocaleDateString('zh-CN');
}

// 防抖函数
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

// 节流函数
function throttle(func, limit) {
    let inThrottle;
    return function(...args) {
        if (!inThrottle) {
            func.apply(this, args);
            inThrottle = true;
            setTimeout(() => inThrottle = false, limit);
        }
    };
}

// 初始化页面动画
function initPageAnimations() {
    const observerOptions = {
        threshold: 0.1,
        rootMargin: '0px 0px -50px 0px'
    };
    
    const scrollObserver = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                entry.target.style.opacity = '1';
                entry.target.style.transform = 'translateY(0)';
            }
        });
    }, observerOptions);
    
    document.querySelectorAll('.card-shadow, .card-hover').forEach(card => {
        card.style.opacity = '0';
        card.style.transform = 'translateY(20px)';
        card.style.transition = 'all 0.6s cubic-bezier(0.4, 0, 0.2, 1)';
        scrollObserver.observe(card);
    });
}

// 添加按钮触摸反馈
function initButtonFeedback() {
    document.querySelectorAll('button').forEach(button => {
        button.addEventListener('mousedown', function() {
            this.style.transform = 'scale(0.95)';
        });
        button.addEventListener('mouseup', function() {
            this.style.transform = 'scale(1)';
        });
        button.addEventListener('mouseleave', function() {
            this.style.transform = 'scale(1)';
        });
    });
}

// 加载中状态
function showLoading(element) {
    const originalText = element.innerHTML;
    element.innerHTML = '<i class="fa fa-spinner fa-spin"></i> 加载中...';
    element.disabled = true;
    
    return () => {
        element.innerHTML = originalText;
        element.disabled = false;
    };
}

// API请求配置
const API_CONFIG = {
    baseURL: GLOBAL_CONFIG.API_BASE_URL,
    timeout: 10000,
    headers: {
        'Content-Type': 'application/json;charset=utf-8',
        'clientid': GLOBAL_CONFIG.CLIENT_ID
    },
    // 访问令牌 - 放在API配置中
    ACCESS_TOKEN: null
};

// 生成UUID
function generateUUID() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        const r = Math.random() * 16 | 0;
        const v = c === 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
}

// 通用API请求函数
async function apiRequest(url, options = {}) {
    const config = {
        method: 'GET',
        headers: { ...API_CONFIG.headers },
        ...options
    };

    // 处理GET请求的查询参数
    if (config.method === 'GET' && options.params) {
        const searchParams = new URLSearchParams(options.params);
        url += (url.includes('?') ? '&' : '?') + searchParams.toString();
        delete config.params;
    }

    // 动态添加Authorization头（如果存在token）
    if (API_CONFIG.ACCESS_TOKEN) {
        config.headers['Authorization'] = `Bearer ${API_CONFIG.ACCESS_TOKEN}`;
    }

    // 添加超时处理
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), API_CONFIG.timeout);
    config.signal = controller.signal;

    try {
        const response = await fetch(API_CONFIG.baseURL + url, config);
        clearTimeout(timeoutId);

        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }

        const data = await response.json();
        
        // 检查业务状态码
        if (data.code !== 200 && data.code !== 0) {
            // 检查是否是Token失效（401错误）
            if (data.code === 401) {
                handleTokenExpired();
                throw new Error('登录状态已过期，请重新登录');
            }
            throw new Error(data.msg || '请求失败');
        }

        return data;
    } catch (error) {
        clearTimeout(timeoutId);
        if (error.name === 'AbortError') {
            throw new Error('请求超时，请稍后重试');
        }
        throw error;
    }
}

// 登录API
async function loginAPI(loginData) {
    return apiRequest('/auth/login', {
        method: 'POST',
        body: JSON.stringify({
            username: loginData.username,
            password: loginData.password,
            code: loginData.code,
            uuid: loginData.uuid,
            clientId: GLOBAL_CONFIG.CLIENT_ID,
            grantType: 'password',
            tenantId: "000000"
        })
    });
}

// 注册API
async function registerAPI(registerData) {
    return apiRequest('/auth/register', {
        method: 'POST',
        body: JSON.stringify({
            username: registerData.username,
            password: registerData.password,
            code: registerData.code,
            uuid: registerData.uuid,
            clientId: GLOBAL_CONFIG.CLIENT_ID,
            grantType: 'password',
            userType: 'app_user',
            tenantId: '000000'
        })
    });
}

// 获取验证码API
async function getCaptchaAPI() {
    return apiRequest('/auth/code', {
        method: 'GET'
    });
}

// 发送短信验证码API
async function sendSmsCodeAPI(phone) {
    return apiRequest('/resource/sms/code', {
        method: 'GET',
        params: {
            phonenumber: phone
        }
    });
}

// 重置密码API
async function resetPasswordAPI(phone, code, newPassword) {
    return apiRequest('/auth/reset-password', {
        method: 'POST',
        body: JSON.stringify({
            phone: phone,
            code: code,
            newPassword: newPassword,
            clientId: GLOBAL_CONFIG.CLIENT_ID,
            tenantId: '000000'
        })
    });
}

// 获取用户信息API
async function getUserInfoAPI() {
    return apiRequest('/system/user/getInfo', {
        method: 'GET'
    });
}

// 登出API
async function logoutAPI() {
    return apiRequest('/auth/logout', {
        method: 'POST'
    });
}

// 上传头像API
async function uploadAvatarAPI(file) {
    const formData = new FormData();
    formData.append('avatarfile', file);
    
    const config = {
        method: 'POST',
        body: formData,
        headers: {
            'clientid': GLOBAL_CONFIG.CLIENT_ID
        }
    };
    
    // 动态添加Authorization头（如果存在token）
    if (API_CONFIG.ACCESS_TOKEN) {
        config.headers['Authorization'] = `Bearer ${API_CONFIG.ACCESS_TOKEN}`;
    }
    
    const response = await fetch(API_CONFIG.baseURL + '/system/user/profile/avatar', config);
    
    if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
    }
    
    const data = await response.json();
    
    // 检查业务状态码
    if (data.code !== 200 && data.code !== 0) {
        if (data.code === 401) {
            handleTokenExpired();
            throw new Error('登录状态已过期，请重新登录');
        }
        throw new Error(data.msg || '上传失败');
    }
    
    return data;
}

// 更新用户头像API
async function updateUserAvatarAPI(avatarUrl) {
    return apiRequest('/system/user/profile', {
        method: 'PUT',
        body: JSON.stringify({
            avatar: avatarUrl
        })
    });
}

// 发布需求API
async function publishDemandAPI(demandData) {
    return apiRequest('/system/demands', {
        method: 'POST',
        body: JSON.stringify({
            title: demandData.demandName,
            categoryId: demandData.demandCategory ? parseInt(demandData.demandCategory) : null,
            intro: demandData.demandIntro,
            content: demandData.demandContent,
            budgetMin: demandData.budgetMin || null,
            budgetMax: demandData.budgetMax || null,
            budgetNegotiable: demandData.budgetNegotiable || 0,
            location: demandData.demandLocation,
            urgency: demandData.demandUrgency || '2',
            contactName: demandData.contactName,
            contactPhone: demandData.contactPhone
        })
    });
}

// 获取需求列表API
async function getDemandsAPI(params = {}) {
    return apiRequest('/system/demands', {
        method: 'GET',
        params: {
            pageNum: params.pageNum || 1,
            pageSize: params.pageSize || 10,
            demandCategory: params.demandCategory || '',
            demandLocation: params.demandLocation || '',
            keyword: params.keyword || ''
        }
    });
}

// 获取需求详情API
async function getDemandDetailAPI(demandId) {
    return apiRequest(`/system/demands/${demandId}`, {
        method: 'GET'
    });
}

// 根据字典类型查询字典数据API
async function getDictDataByTypeAPI(dictType) {
    return apiRequest(`/system/dict/data/type/${dictType}`, {
        method: 'GET'
    });
}

// 判断是否为商户API
async function checkIsMerchantAPI() {
    return apiRequest('/business/merchant/isMerchant', {
        method: 'GET'
    });
}

// 新增商户信息API
async function addMerchantInfoAPI(merchantData) {
    return apiRequest('/business/merchant', {
        method: 'POST',
        body: JSON.stringify({
            merchantCategory: merchantData.merchantCategory, // 多个类型用逗号分隔，如："1,2,3"
            merchantName: merchantData.merchantName,
            creditCode: merchantData.creditCode, // 统一社会信用代码
            contactPerson: merchantData.contactPerson,
            contactPhone: merchantData.contactPhone
        })
    });
}

// 获取我的商户信息API
async function getMyMerchantInfoAPI() {
    return apiRequest('/business/merchant/myMerchantInfo', {
        method: 'GET'
    });
}

// 获取全局配置
function getGlobalConfig() {
    return GLOBAL_CONFIG;
}

// 设置全局配置
function setGlobalConfig(config) {
    Object.assign(GLOBAL_CONFIG, config);
    // 更新API配置
    API_CONFIG.baseURL = GLOBAL_CONFIG.API_BASE_URL;
    API_CONFIG.headers.clientid = GLOBAL_CONFIG.CLIENT_ID;
}

// Token失效处理函数
function handleTokenExpired() {
    // 清除Token
    clearAccessToken();
    
    // 清除用户信息
    localStorage.removeItem('currentUser');
    localStorage.removeItem('isLoggedIn');
    
    // 显示提示
    showToast('登录状态已过期，请重新登录', 'warning');
    
    // 延迟跳转到登录页面
    setTimeout(() => {
        // 检查当前是否在登录页面，避免重复跳转
        if (!window.location.pathname.includes('login.html')) {
            window.location.href = './pages/login.html';
        }
    }, 2000);
}

// Token管理函数
function setAccessToken(token) {
    API_CONFIG.ACCESS_TOKEN = token;
    // 同时保存到localStorage
    if (token) {
        localStorage.setItem('access_token', token);
    } else {
        localStorage.removeItem('access_token');
    }
}

function getAccessToken() {
    // 优先从API配置获取，如果为空则从localStorage获取
    if (API_CONFIG.ACCESS_TOKEN) {
        return API_CONFIG.ACCESS_TOKEN;
    }
    
    const storedToken = localStorage.getItem('access_token');
    if (storedToken) {
        API_CONFIG.ACCESS_TOKEN = storedToken;
        return storedToken;
    }
    
    return null;
}

function clearAccessToken() {
    API_CONFIG.ACCESS_TOKEN = null;
    localStorage.removeItem('access_token');
}

// 初始化时从localStorage恢复token
function initToken() {
    const storedToken = localStorage.getItem('access_token');
    if (storedToken) {
        API_CONFIG.ACCESS_TOKEN = storedToken;
    }
}

// 检查登录状态
function isLoggedIn() {
    const token = getAccessToken();
    const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true';
    return !!(token && isLoggedIn);
}

// 检查是否需要登录
function checkLoginRequired(action, actionName) {
    if (!isLoggedIn()) {
        showLoginRequiredModal(actionName);
        return false;
    }
    return true;
}

// 显示登录提示弹窗
function showLoginRequiredModal(actionName) {
    const modal = document.createElement('div');
    modal.className = 'fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4';
    modal.innerHTML = `
        <div class="bg-white rounded-2xl shadow-2xl max-w-sm w-full mx-4 transform transition-all duration-300">
            <div class="p-6">
                <!-- 弹窗头部 -->
                <div class="flex items-center justify-center mb-4">
                    <div class="w-16 h-16 rounded-full bg-primary/10 flex items-center justify-center">
                        <i class="fa fa-user-lock text-primary text-2xl"></i>
                    </div>
                </div>
                
                <!-- 弹窗内容 -->
                <div class="text-center mb-6">
                    <h3 class="text-lg font-bold text-text-primary mb-2">需要登录</h3>
                    <p class="text-sm text-text-secondary leading-relaxed">
                        使用"${actionName}"功能需要先登录账号，是否前往登录页面？
                    </p>
                </div>
                
                <!-- 弹窗按钮 -->
                <div class="flex gap-3">
                    <button onclick="CommonUtils.hideLoginRequiredModal()"
                            class="flex-1 px-4 py-3 bg-gray-100 text-text-primary rounded-xl font-medium hover:bg-gray-200 transition-colors">
                        取消
                    </button>
                    <button onclick="CommonUtils.goToLogin()"
                            class="flex-1 px-4 py-3 bg-primary text-white rounded-xl font-medium hover:bg-primary-dark transition-colors">
                        去登录
                    </button>
                </div>
            </div>
        </div>
    `;
    
    document.body.appendChild(modal);
    
    // 阻止背景滚动
    document.body.style.overflow = 'hidden';
    
    // 添加点击背景关闭功能
    modal.onclick = function(e) {
        if (e.target === modal) {
            hideLoginRequiredModal();
        }
    };
}

// 隐藏登录提示弹窗
function hideLoginRequiredModal() {
    const modal = document.querySelector('.fixed.inset-0.bg-black.bg-opacity-50.z-50');
    if (modal) {
        modal.remove();
        // 恢复背景滚动
        document.body.style.overflow = '';
    }
}

// 跳转到登录页面
function goToLogin() {
    hideLoginRequiredModal();
    // 判断当前路径，决定登录页面的相对路径
    const currentPath = window.location.pathname;
    if (currentPath.includes('/pages/')) {
        window.location.href = './login.html';
    } else {
        window.location.href = './pages/login.html';
    }
}

// 需要登录的功能包装函数
function requireLogin(action, actionName) {
    return function() {
        if (checkLoginRequired(action, actionName)) {
            action();
        }
    };
}

// 检查是否需要商户权限
async function checkMerchantRequired(action, actionName) {
    // 先检查登录状态
    if (!isLoggedIn()) {
        showLoginRequiredModal(actionName);
        return false;
    }
    
    // 检查商户认证状态
    try {
        const result = await checkIsMerchantAPI();
        
        // 根据返回结果判断商户状态
        // auditStatus: 0-已审核, 1-待审核, 2-驳回
        if (result.code === 200 || result.code === 0) {
            const isMerchant = result.data?.isMerchant || result.data?.verified || false;
            const auditStatus = result.data?.auditStatus;
            
            if (isMerchant || auditStatus === '0' || auditStatus === 0) {
                // 已审核/已认证商户，允许操作
                return true;
            } else if (auditStatus === '1' || auditStatus === 1) {
                // 待审核
                showMerchantAuthPendingModal(actionName);
                return false;
            } else if (auditStatus === '2' || auditStatus === 2) {
                // 驳回，可重新提交
                showMerchantAuthRejectedModal(actionName);
                return false;
            } else {
                // 未认证
                showMerchantAuthRequiredModal(actionName);
                return false;
            }
        } else {
            // API返回错误，默认为未认证
            showMerchantAuthRequiredModal(actionName);
            return false;
        }
    } catch (error) {
        console.error('检查商户认证状态失败:', error);
        // 发生错误，提示用户
        showMerchantAuthRequiredModal(actionName);
        return false;
    }
}

// 显示商户认证必需提示弹窗
function showMerchantAuthRequiredModal(actionName) {
    const modal = document.createElement('div');
    modal.className = 'fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4';
    modal.innerHTML = `
        <div class="bg-white rounded-2xl shadow-2xl max-w-sm w-full mx-4 transform transition-all duration-300">
            <div class="p-6">
                <!-- 弹窗头部 -->
                <div class="flex items-center justify-center mb-4">
                    <div class="w-16 h-16 rounded-full bg-primary/10 flex items-center justify-center">
                        <i class="fa fa-store text-primary text-2xl"></i>
                    </div>
                </div>
                
                <!-- 弹窗内容 -->
                <div class="text-center mb-6">
                    <h3 class="text-lg font-bold text-text-primary mb-2">需要商户认证</h3>
                    <p class="text-sm text-text-secondary leading-relaxed">
                        使用"${actionName}"功能需要先完成商户认证，是否前往认证？
                    </p>
                </div>
                
                <!-- 弹窗按钮 -->
                <div class="flex gap-3">
                    <button onclick="CommonUtils.hideMerchantAuthRequiredModal()"
                            class="flex-1 px-4 py-3 bg-gray-100 text-text-primary rounded-xl font-medium hover:bg-gray-200 transition-colors">
                        取消
                    </button>
                    <button onclick="CommonUtils.goToMerchantAuth()"
                            class="flex-1 px-4 py-3 bg-primary text-white rounded-xl font-medium hover:bg-primary-dark transition-colors">
                        去认证
                    </button>
                </div>
            </div>
        </div>
    `;
    
    document.body.appendChild(modal);
    
    // 阻止背景滚动
    document.body.style.overflow = 'hidden';
    
    // 添加点击背景关闭功能
    modal.onclick = function(e) {
        if (e.target === modal) {
            hideMerchantAuthRequiredModal();
        }
    };
}

// 显示商户认证待审核提示弹窗
function showMerchantAuthPendingModal(actionName) {
    const modal = document.createElement('div');
    modal.className = 'fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4';
    modal.innerHTML = `
        <div class="bg-white rounded-2xl shadow-2xl max-w-sm w-full mx-4 transform transition-all duration-300">
            <div class="p-6">
                <!-- 弹窗头部 -->
                <div class="flex items-center justify-center mb-4">
                    <div class="w-16 h-16 rounded-full bg-accent/10 flex items-center justify-center">
                        <i class="fa fa-clock-o text-accent text-2xl"></i>
                    </div>
                </div>
                
                <!-- 弹窗内容 -->
                <div class="text-center mb-6">
                    <h3 class="text-lg font-bold text-text-primary mb-2">商户认证待审核</h3>
                    <p class="text-sm text-text-secondary leading-relaxed">
                        您的商户认证申请正在审核中，审核通过后即可使用"${actionName}"功能，请耐心等待。
                    </p>
                </div>
                
                <!-- 弹窗按钮 -->
                <div class="flex gap-3">
                    <button onclick="CommonUtils.hideMerchantAuthPendingModal()"
                            class="flex-1 px-4 py-3 bg-primary text-white rounded-xl font-medium hover:bg-primary-dark transition-colors">
                        我知道了
                    </button>
                </div>
            </div>
        </div>
    `;
    
    document.body.appendChild(modal);
    
    // 阻止背景滚动
    document.body.style.overflow = 'hidden';
    
    // 添加点击背景关闭功能
    modal.onclick = function(e) {
        if (e.target === modal) {
            hideMerchantAuthPendingModal();
        }
    };
}

// 隐藏商户认证必需提示弹窗
function hideMerchantAuthRequiredModal() {
    const modals = document.querySelectorAll('.fixed.inset-0.bg-black.bg-opacity-50.z-50');
    modals.forEach(modal => {
        if (modal.innerHTML.includes('需要商户认证') || modal.innerHTML.includes('去认证')) {
            modal.remove();
            // 恢复背景滚动
            document.body.style.overflow = '';
        }
    });
}

// 隐藏商户认证待审核提示弹窗
function hideMerchantAuthPendingModal() {
    const modals = document.querySelectorAll('.fixed.inset-0.bg-black.bg-opacity-50.z-50');
    modals.forEach(modal => {
        if (modal.innerHTML.includes('商户认证待审核') || modal.innerHTML.includes('我知道了')) {
            modal.remove();
            // 恢复背景滚动
            document.body.style.overflow = '';
        }
    });
}

// 显示商户认证驳回提示弹窗
function showMerchantAuthRejectedModal(actionName) {
    const modal = document.createElement('div');
    modal.className = 'fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4';
    modal.innerHTML = `
        <div class="bg-white rounded-2xl shadow-2xl max-w-sm w-full mx-4 transform transition-all duration-300">
            <div class="p-6">
                <!-- 弹窗头部 -->
                <div class="flex items-center justify-center mb-4">
                    <div class="w-16 h-16 rounded-full bg-red-100 flex items-center justify-center">
                        <i class="fa fa-times-circle text-red-600 text-2xl"></i>
                    </div>
                </div>
                
                <!-- 弹窗内容 -->
                <div class="text-center mb-6">
                    <h3 class="text-lg font-bold text-text-primary mb-2">商户认证已驳回</h3>
                    <p class="text-sm text-text-secondary leading-relaxed">
                        您的商户认证申请已被驳回，使用"${actionName}"功能需要先通过商户认证。请前往"我的"页面查看驳回原因并重新提交认证申请。
                    </p>
                </div>
                
                <!-- 弹窗按钮 -->
                <div class="flex gap-3">
                    <button onclick="CommonUtils.hideMerchantAuthRejectedModal()"
                            class="flex-1 px-4 py-3 bg-gray-100 text-text-primary rounded-xl font-medium hover:bg-gray-200 transition-colors">
                        我知道了
                    </button>
                    <button onclick="CommonUtils.goToMerchantAuth()"
                            class="flex-1 px-4 py-3 bg-primary text-white rounded-xl font-medium hover:bg-primary-dark transition-colors">
                        重新认证
                    </button>
                </div>
            </div>
        </div>
    `;
    
    document.body.appendChild(modal);
    
    // 阻止背景滚动
    document.body.style.overflow = 'hidden';
    
    // 添加点击背景关闭功能
    modal.addEventListener('click', (e) => {
        if (e.target === modal) {
            hideMerchantAuthRejectedModal();
        }
    });
}

// 隐藏商户认证驳回提示弹窗
function hideMerchantAuthRejectedModal() {
    const modals = document.querySelectorAll('.fixed.inset-0.bg-black.bg-opacity-50.z-50');
    modals.forEach(modal => {
        if (modal.innerHTML.includes('商户认证已驳回') || modal.innerHTML.includes('重新认证')) {
            modal.remove();
            // 恢复背景滚动
            document.body.style.overflow = '';
        }
    });
}

// 跳转到商户认证页面
function goToMerchantAuth() {
    hideMerchantAuthRequiredModal();
    // 判断当前路径，决定目标页面的相对路径
    const currentPath = window.location.pathname;
    
    // 设置标记，表示需要打开商户认证弹窗
    sessionStorage.setItem('openMerchantAuth', 'true');
    
    if (currentPath.includes('/pages/')) {
        window.location.href = './my.html';
    } else {
        window.location.href = './pages/my.html';
    }
}

// 需要商户权限的功能包装函数
function requireMerchant(action, actionName) {
    return async function() {
        const hasPermission = await checkMerchantRequired(action, actionName);
        if (hasPermission) {
            action();
        }
    };
}

// 导出所有函数
window.CommonUtils = {
    smoothScrollTo,
    createRipple,
    showToast,
    clearAllToasts,
    formatDate,
    debounce,
    throttle,
    initPageAnimations,
    initButtonFeedback,
    showLoading,
    // API相关函数
    generateUUID,
    apiRequest,
    loginAPI,
    registerAPI,
    getCaptchaAPI,
    sendSmsCodeAPI,
    resetPasswordAPI,
    getUserInfoAPI,
    logoutAPI,
    uploadAvatarAPI,
    updateUserAvatarAPI,
    publishDemandAPI,
    getDemandsAPI,
    getDemandDetailAPI,
    getDictDataByTypeAPI,
    checkIsMerchantAPI,
    addMerchantInfoAPI,
    getMyMerchantInfoAPI,
    // 配置管理函数
    getGlobalConfig,
    setGlobalConfig,
    // Token管理函数
    setAccessToken,
    getAccessToken,
    clearAccessToken,
    initToken,
    handleTokenExpired,
    // 登录检查函数
    isLoggedIn,
    checkLoginRequired,
    showLoginRequiredModal,
    hideLoginRequiredModal,
    goToLogin,
    requireLogin,
    // 商户权限检查函数
    checkMerchantRequired,
    showMerchantAuthRequiredModal,
    showMerchantAuthPendingModal,
    showMerchantAuthRejectedModal,
    hideMerchantAuthRequiredModal,
    hideMerchantAuthPendingModal,
    hideMerchantAuthRejectedModal,
    goToMerchantAuth,
    requireMerchant
};

